﻿using System;
using System.Drawing;

using SharedGenomics.Workbench.Core;
using SharedGenomics.Workbench.Views;
using SharedGenomics.Annotations;
using SharedGenomics.Workbench.Messages;
using SharedGenomics.Workbench.Services;

namespace SharedGenomics.Workbench.Presenters
{
    public class AnnotationWrapperPresenter : Presenter
    {
        private IPresenter wrappedPresenter;

        public AnnotationWrapperPresenter(IAnnotationWrapperView view, IAnnotationNotifier notifier)
            : base(view)
        {
            this.WrapperView = view;
            this.AnnotationNotifier = notifier;

            //register for view events
            view.CommentButtonClicked += this.View_CommentButtonClicked;
            view.ImportanceChanged += this.View_ImportanceChanged;
            view.ViewedAnnotationIdChanged += this.View_ViewedAnnotationIdChanged;
            view.Shown += View_Shown;
        }

        private void View_Shown(object sender, EventArgs e)
        {
            IAnnotationPresenter annotationPresenter = this.WrappedPresenter as IAnnotationPresenter;
            if (annotationPresenter != null && this.SnapshotOnOpen)
            {
                //notify a new annotation has been shown
                Image img = this.WrapperView.GetViewImage();
                IAnnotation wrappedAnnotation = annotationPresenter.Annotation;
                this.AnnotationId = Guid.NewGuid();

                this.AnnotationNotifier.CaptureAnnotation(this.AnnotationId, wrappedAnnotation, img);
            }
        }

        private void View_ViewedAnnotationIdChanged(object sender, ViewedAnnotationIdChangedEventArgs e)
        {
            this.AnnotationId = e.ViewedAnnotationId;
        }

        private void View_ImportanceChanged(object sender, EventArgs e)
        {
            this.AnnotationNotifier.SetAnnotationImportance(this.AnnotationId, this.WrapperView.IsImportant);
        }

        private void View_CommentButtonClicked(object sender, EventArgs e)
        {
            if (!Guid.Empty.Equals(this.AnnotationId))
            {
                // TODO: Show comment presenter
            }
        }

        private IAnnotationWrapperView WrapperView { get; set; }
        private IAnnotationNotifier AnnotationNotifier { get; set; }

        //NOTE: protected for testing purposes...
        protected Guid AnnotationId { get; set; }

        [Region("Wrapped")]
        public IPresenter WrappedPresenter
        {
            get { return this.wrappedPresenter; }
            set
            {
                if (value != null)
                {
                    this.WrapperView.WrappedViewTitle = value.View.Title;
                }

                this.wrappedPresenter = value;
            }
        }

        public override bool SnapshotOnOpen
        {
            get { return WrappedPresenter.SnapshotOnOpen; }
        }
    }
}
